package com.nercel.dsj.gksales.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.nercel.dsj.gksales.exception.ExceptionUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author qinshuangxi
 * @date 2020-06-12 发送短信的工具类（阿里云短信服务）
 */
@Slf4j
@Component
public class AliSmsUtil {

    @Value("${aliyun.regionId}")
    private String regionId;

    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.accessSecret}")
    private String accessSecret;

    @Value("${aliyun.sms.signName}")
    private String signName;

    @Async
    public void sendSms(String to, String templateCode, String jsonContent) {
        log.info("【阿里云短信】sendSms,参数列表：to:[{}],templateCode:[{}],jsonContent:[{}]", to, templateCode, jsonContent);
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessSecret);
        log.info("【阿里云短信】sendSms,profile,regionId:{},accessKeyId:{},accessSecret:{}", regionId, accessKeyId,
            accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        log.info("【阿里云短信】sendSms,client,{}", client.toString());
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("PhoneNumbers", to);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", jsonContent);
        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info("【阿里云短信】sendSms,response,{}", response.toString());
            int httpStatus = response.getHttpStatus();
            if (httpStatus == 200) {
                log.info("【阿里云短信】向:{}发送短信成功，短信模板：{}，短信内容：{}，返回内容：{}", to, templateCode, jsonContent,response.getData());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("【阿里云短信】向:{}发送短信失败，短信模板：{}，短信内容：{}", to, templateCode, jsonContent);
        }
    }

    /**
     * @param templateCode
     *            模板代码
     * @param phoneNumberJson
     *            接收短信的手机号码，JSON数组格式。示例：["15211111111","15311111111"]
     * @param templateParamJson
     *            短信模板变量对应的实际值。示例： [{"password":"123456"},{"password":"123456"}]
     *            <p>
     *            批量发送短信的接口注意不要只发一条，发一条会失败，如果只发一条请使用
     *            <p>
     *            在一次请求中，最多可以向100个手机号码分别发送短信
     */
    @Async
    public void sendBatchSms(String templateCode, String phoneNumberJson, String templateParamJson) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        JsonArray jsonArray = new JsonParser().parse(phoneNumberJson).getAsJsonArray();// 获取JsonArray对象
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendBatchSms");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("PhoneNumberJson", phoneNumberJson);
        request.putQueryParameter("SignNameJson", repeatJsonString(signName, jsonArray.size()));
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParamJson", templateParamJson);
        try {
            CommonResponse response = client.getCommonResponse(request);
            int httpStatus = response.getHttpStatus();
            if (httpStatus == 200) {
                log.info("【阿里云短信】向:{}发送批量短信成功，短信模板：{}，短信内容：{}，返回数据：{}", phoneNumberJson, templateCode, templateParamJson,response.getData());
            }
        } catch (Exception e) {
            ExceptionUtil.printStackTrace2Log(e, log);
            log.info("【阿里云短信】向:{}发送批量短信失败，短信模板：{}，短信内容：{}", phoneNumberJson, templateCode, templateParamJson);
        }
    }

    private String repeatJsonString(String str, int times) {
        Assert.isTrue(times > 0, "times只能传正整数！");
        JsonArray jsonArray = new JsonArray();
        for (int i = 0; i < times; i++) {
            jsonArray.add(str);
        }
        log.info(jsonArray.toString());
        return jsonArray.toString();
    }

}
